package movieGandalf.dbParser;

import java.io.BufferedReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import movieGandalf.database.MovieTools;

public class LanguagesReader implements DataReader{
	
	public int read(Connection conn, BufferedReader in){
		String line = null;
		Set<String> languages = new HashSet<String>();
		String language = null;
		
		try {
			boolean isBegin = true;
			while ((line = in.readLine()) != null){
				if (isBegin){
					if ((line.length()<3 || !line.subSequence(0, 3).equals("===")))
						continue;
					else{
						isBegin = false;
						continue;
					}
				}
				
				int stringEnd = line.length();
				int i = 0;
				for (i = line.length()-1;i>=0;i--){
					if (line.charAt(i)==')') {
						while (i>=0 && line.charAt(i)!='(')
							i--;
						i--;
						stringEnd=i;
						continue;
					}
					if (line.charAt(i)=='\t'){
						i++;
						break;
					}
				}
				
				if (i<0)
					continue;
				
				if (stringEnd-i<=2) // For ignoring errors on original file.
					continue;
				
				language = line.substring(i, stringEnd);
				if (!MovieTools.languageValidator(language))
					continue;
				
				languages.add(language);
			}
			

			PreparedStatement stmt = conn.prepareStatement(new String("REPLACE INTO Languages (language) VALUES (?)"));
			
			Iterator<String> iter = languages.iterator();
			
			while (iter.hasNext()){
				language = iter.next();
				stmt.setString(1, language);
				stmt.addBatch();
			}

			try{
				stmt.executeBatch();
			}
			catch(Exception e){}
			finally{
				conn.commit();
				stmt.close();
			}
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
